<template>
  <header class="header">
    <div class="nav-container">
      <!-- 左侧Logo和标题 -->
      <div class="logo-section">
        <div class="logo">
          <slot name="logo">
            <span>{{ logoTitle.charAt(0) }}</span>
          </slot>
        </div>
        <h1 class="logo-title">{{ logoTitle }}</h1>
      </div>

      <!-- 中间导航链接 -->
      <nav class="nav-links">
        <a
          v-for="link in navLinks"
          :key="link.path"
          :href="link.path"
          class="nav-link"
          :class="{ active: link.active }"
          @click.prevent="handleNavClick(link)"
        >
          {{ link.name }}
        </a>
      </nav>

      <!-- 右侧用户菜单 -->
      <div class="user-menu" @click="toggleDropdown">
        <button class="user-btn" aria-expanded="isDropdownOpen">
          <div class="avatar">
            <slot name="avatar">
              {{ userInfo.avatar || userInfo.name.charAt(0) }}
            </slot>
          </div>
          <span class="user-name">{{ userInfo.name }}</span>
        </button>
        <div class="dropdown-menu" :class="{ show: isDropdownOpen }">
          <a
            v-for="(item, index) in dropdownItems"
            :key="index"
            v-if="!item.divider"
            :href="item.path"
            class="dropdown-item"
            @click.prevent="handleDropdownClick(item)"
          >
            {{ item.name }}
          </a>
          <hr v-else class="dropdown-divider" />
        </div>
      </div>
    </div>
  </header>
</template>

<script>
export default {
  name: 'HeaderNavigation',
  props: {
    logoTitle: {
      type: String,
      default: 'Vue App'
    },
    navLinks: {
      type: Array,
      default: () => [
        { name: '首页', path: '/', active: true }
      ]
    },
    userInfo: {
      type: Object,
      default: () => ({
        name: '用户',
        avatar: 'U'
      })
    },
    dropdownItems: {
      type: Array,
      default: () => [
        { name: '个人中心', path: '/profile' },
        { name: '退出登录', path: '/logout' }
      ]
    }
  },
  data() {
    return {
      isDropdownOpen: false
    }
  },
  mounted() {
    // 监听点击外部关闭下拉菜单
    document.addEventListener('click', this.handleClickOutside)
  },
  beforeUnmount() {
    document.removeEventListener('click', this.handleClickOutside)
  },
  methods: {
    toggleDropdown(event) {
      event.stopPropagation()
      this.isDropdownOpen = !this.isDropdownOpen
    },
    handleNavClick(link) {
      // 更新激活状态
      this.$emit('nav-click', link)
    },
    handleDropdownClick(item) {
      this.isDropdownOpen = false
      this.$emit('dropdown-click', item)
    },
    handleClickOutside(event) {
      if (!this.$el.contains(event.target)) {
        this.isDropdownOpen = false
      }
    }
  }
}
</script>

<style scoped>
/* 组件样式已在全局style.css中定义 */
</style>